package com.jueban.serviceImpl;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.jueban.service.FileConversionService;
import org.junit.Test;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;

@Service
public class FileConversionServiceImpl implements FileConversionService
{



    @Override
    public void doc2Pdf(File docFile)
    {
        int wdFormatPDF = 17;
        System.out.println("启动Word...");
        long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        Dispatch doc = null;
        try
        {
            app = new ActiveXComponent("Word.Application");
            app.setProperty("Visible", new Variant(false));
            Dispatch docs = app.getProperty("Documents").toDispatch();

            String sfileName = docFile.getPath();
            String path = docFile.getAbsolutePath();
            String[] p = path.split("\\.");
            String toFileName = "";
            if(p.length > 2)
            {
                for(int i = 0; i < p.length - 1; i++)
                {
                    toFileName += p[i] + ".";
                }
                toFileName += "pdf";
            }
            else
            {
                toFileName = p[0] + ".pdf";
            }
            System.out.println(toFileName);

            doc = Dispatch.call(docs, "Open", sfileName).toDispatch();
            System.out.println("打开文档..." + sfileName);
            System.out.println("转换文档到PDF..." + toFileName);
            File tofile = new File(toFileName);
            if (tofile.exists())
            {
                tofile.delete();
            }
            Dispatch.call(doc, "SaveAs", toFileName, // FileName
                    wdFormatPDF);
            long end = System.currentTimeMillis();
            System.out.println("转换完成..用时：" + (end - start) + "ms.");


        } catch (Exception e)
        {
            System.out.println("========Error:文档转换失败：" + e.getMessage());
        } finally
        {
            Dispatch.call(doc, "Close", false);
            System.out.println("关闭文档");
            if (app != null)
                app.invoke("Quit", new Variant[]{});
        }
        //如果没有这句话,winword.exe进程将不会关闭
        ComThread.Release();
    }

    @Test
    public void test()
    {
        File docFile = new File("C:/Users/HQ/Desktop/知识产权管理系统软件详细设计编写说明书.doc");
        doc2Pdf(docFile);
    }

}
